//
//  DialectProxy.m
//  DialectShare
//
//  Created by timmy zhong on 3/20/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DialectProxy.h"
#import "PathHelper.h"
#import "ASIHTTPRequest.h"
#import "DialectDB.h"
#import "Dialect.h"
#import "YuXi.h"
#import "YuXiDB.h"
#import "User.h"
#import "UserDB.h"
#import "Comment.h"
#import "CommentDB.h"
#import "JSON.h"

@interface DialectProxy ()
- (void)backgroundAroundWithParameters:(NSDictionary *)parameters;
- (void)backgroundYuXis;
- (void)backgroundDialectsOfYuXi:(YuXi *)yuxi;
- (void)backgroundFeeds;
- (void)backgroundGoodbad:(NSDictionary *)parameters;
- (void)backgroundCommentsOfDialect:(Dialect *)dialect;
- (void)backgroundSendComment:(Comment *)comment;
- (void)backgroundGetAddress:(NSDictionary *)parameters;
- (void)backgroundDialectsOfUser:(User *)user;
- (void)backgroundSearchTerm:(NSString *)term;
- (void)storeDialects:(NSArray *)dialects;
@end

@implementation DialectProxy

- (id)initWithDelegate:(NSObject<ProxyDelegate> *)delegate
{
    self = [super init];
    if (self) {
        self.delegate = delegate;
    }
    
    return self;
}

- (void)storeDialects:(NSArray *)dialectArr
{
    NSMutableArray *dialects = [[NSMutableArray alloc] initWithCapacity:20];
    NSMutableArray *users = [[NSMutableArray alloc] initWithCapacity:20];
    for (NSDictionary *d in dialectArr) {
        
        Dialect *dia = [Dialect dialectWithDic:d];
        [dialects addObject:dia];
        
        User *user = [User userWithDic:[d objectForKey:@"user"]];
        [users addObject:user];
        
    }
    
    DialectDB *db = [[DialectDB alloc] init];
    [db addDialects:dialects];
    [db release];
    
    UserDB *userDB = [[UserDB alloc] init];
    [userDB addUsers:users];
    [userDB release];
}

- (void)aroundLongitude:(float)longitude latitude:(float)latitude page:(int)page count:(int)count
{
    if ([self connectToNetwork]) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithCapacity:20];
        [dic setObject:[NSString stringWithFormat:@"%f", longitude] forKey:@"lng"];
        [dic setObject:[NSString stringWithFormat:@"%f", latitude] forKey:@"lat"];
        [dic setObject:[NSString stringWithFormat:@"%d", page] forKey:@"page"];
        [dic setObject:[NSString stringWithFormat:@"%d", count] forKey:@"count"];
        [self performSelectorInBackground:@selector(backgroundAroundWithParameters:) withObject:dic];
        [dic release];
    } else {
        [self.delegate requestFinishWithProxy:self];
    }
}

- (void)backgroundAroundWithParameters:(NSDictionary *)parameters
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *lng = [parameters objectForKey:@"lng"];
    NSString *lat = [parameters objectForKey:@"lat"];
    NSString *page = [parameters objectForKey:@"page"];
    NSString *count = [parameters objectForKey:@"count"];
    
    NSString *url = [[PathHelper baseUrl] stringByAppendingFormat:@"c=main&a=around&lng=%@&lat=%@&page=%@&count=%@&auth=%@", lng, lat, page, count, [User current].auth];

    NSString *data = [self fetchDataForUrlString:url];
    NSDictionary *rtn = [self parse:data];
    if ([[rtn objectForKey:@"st"] intValue] == ServerStatusSuccess) {
        NSArray *dialectArr = [rtn objectForKey:@"rs"];
        [self performSelectorOnMainThread:@selector(storeDialects:) withObject:dialectArr waitUntilDone:YES];
        
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    }
    
    [pool release];
}

- (void)yuxis
{
    if ([self connectToNetwork]) {
        [self performSelectorInBackground:@selector(backgroundYuXis) withObject:nil];
    } else {
        [self.delegate requestFinishWithProxy:self];
    }
}

- (void)backgroundYuXis
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *url = [[PathHelper baseUrl] stringByAppendingString:@"c=main&a=yuxi"];
    
    NSString *data = [self fetchDataForUrlString:url];
    NSDictionary *rtn = [self parse:data];
    if ([[rtn objectForKey:@"st"] intValue] == ServerStatusSuccess) {
        NSArray *yuxiArr = [rtn objectForKey:@"rs"];
        NSMutableArray *yuxis = [[NSMutableArray alloc] initWithCapacity:20];
        for (NSDictionary *d in yuxiArr) {
            
            YuXi *yuxi = [YuXi yuxiWithDic:d];
            [yuxis addObject:yuxi];
        }
        
        YuXiDB *db = [[YuXiDB alloc] init];
        [db performSelectorOnMainThread:@selector(addYuXis:) withObject:yuxis waitUntilDone:YES];
        [db release];
        
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    }
    
    
    [pool release];
}


- (void)dialectsOfYuXi:(YuXi *)yuxi
{
    if ([self connectToNetwork]) {
        [self performSelectorInBackground:@selector(backgroundDialectsOfYuXi:) withObject:yuxi];
    } else {
        [self.delegate requestFinishWithProxy:self];
    }
}

- (void)backgroundDialectsOfYuXi:(YuXi *)yuxi
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *url = [[PathHelper baseUrl] stringByAppendingFormat:@"c=main&a=yuxi_dialects&yuxi=%d", yuxi.yuxiId];
    
    NSString *data = [self fetchDataForUrlString:url];
    NSDictionary *rtn = [self parse:data];
    if ([[rtn objectForKey:@"st"] intValue] == ServerStatusSuccess) {
        NSArray *dialectArr = [rtn objectForKey:@"rs"];
        [self performSelectorOnMainThread:@selector(storeDialects:) withObject:dialectArr waitUntilDone:YES];
        
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    }
    
    [pool release];
}


- (void)feeds
{
    if ([self connectToNetwork]) {
        [self performSelectorInBackground:@selector(backgroundFeeds) withObject:nil];
    } else {
        [self.delegate requestFinishWithProxy:self];
    }
}

- (void)backgroundFeeds
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    User *user = [User current];
    NSString *url = [[PathHelper baseUrl] stringByAppendingFormat:@"c=user&a=feed&auth=%@", user.auth];
    NSString *data = [self fetchDataForUrlString:url];
    NSDictionary *rtn = [self parse:data];
    if ([[rtn objectForKey:@"st"] intValue] == ServerStatusSuccess) {
        NSArray *dialectArr = [rtn objectForKey:@"rs"];
        [self performSelectorOnMainThread:@selector(storeDialects:) withObject:dialectArr waitUntilDone:YES];
        
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    } else if ([[rtn objectForKey:@"st"] intValue] == ServerStatusEmpty) {
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    }
    [pool release];
}

- (void)goodbad:(BOOL)isGood dialect:(Dialect *)dialect
{
    if ([self connectToNetwork]) {
        NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:dialect, @"dialect", [NSNumber numberWithBool:isGood], @"isGood", nil];
        [self performSelectorInBackground:@selector(backgroundGoodbad:) withObject:parameters];
    } else {
        [self.delegate requestFinishWithProxy:self];
    }
}

- (void)backgroundGoodbad:(NSDictionary *)parameters
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSNumber *isGood = [parameters objectForKey:@"isGood"];
    Dialect *dialect = [parameters objectForKey:@"dialect"];
    BOOL good = [isGood boolValue];
    NSString *type = @"good";
    if (!good) {
        type = @"bad";
    }
    NSString *url = [[PathHelper baseUrl] stringByAppendingFormat:@"c=user&a=gb&type=%@&id=%d", type, dialect.dialectId];
    NSString *data = [self fetchDataForUrlString:url];
    NSDictionary *rtn = [self parse:data];
    if ([[rtn objectForKey:@"st"] intValue] == ServerStatusSuccess) {
        
        self.object = isGood;
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    }

    [pool release];
}

- (void)commentsOfDialect:(Dialect *)dialect
{
    if ([self connectToNetwork]) {
        [self performSelectorInBackground:@selector(backgroundCommentsOfDialect:) withObject:dialect];
    } else {
        [self.delegate requestFinishWithProxy:self];
    }
}

- (void)backgroundCommentsOfDialect:(Dialect *)dialect
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    NSString *url = [[PathHelper baseUrl] stringByAppendingFormat:@"c=main&a=comment&id=%d", dialect.dialectId];
    NSString *data = [self fetchDataForUrlString:url];
    NSDictionary *rtn = [self parse:data];
    if ([[rtn objectForKey:@"st"] intValue] == ServerStatusSuccess) {
        NSArray *commentArr = [rtn objectForKey:@"rs"];
        NSMutableArray *comments = [[NSMutableArray alloc] initWithCapacity:20];
        NSMutableArray *users = [[NSMutableArray alloc] initWithCapacity:20];
        for (NSDictionary *dic in commentArr) {
            Comment *comment = [Comment commentWithDic:dic];
            User *user = [User userWithDic:[dic objectForKey:@"user"]];
            [comments addObject:comment];
            [users addObject:user];
        }
        
        CommentDB *commentDB = [[CommentDB alloc] init];
        [commentDB performSelectorOnMainThread:@selector(addComments:) withObject:comments waitUntilDone:YES];
        [commentDB release];
        UserDB *userDB = [[UserDB alloc] init];
        [userDB performSelectorOnMainThread:@selector(addUsers:) withObject:users waitUntilDone:YES];
        [userDB release];
        
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    }
    
    [pool release];
}

- (void)getAddress:(float)longitude latitude:(float)latitude
{
    if ([self connectToNetwork]) {
    
        NSDictionary *paramaters = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithFloat:longitude], @"lng", [NSNumber numberWithFloat:latitude], @"lat", nil];
        [self performSelectorInBackground:@selector(backgroundGetAddress:) withObject:paramaters];
        [paramaters release];

    } else {
        [self.delegate requestFinishWithProxy:self];
    }
}

- (void)backgroundGetAddress:(NSDictionary *)parameters
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    float lng = [[parameters objectForKey:@"lng"] floatValue];
    float lat = [[parameters objectForKey:@"lat"] floatValue];
    NSString *url = [NSString stringWithFormat:@"http://api.map.qq.com/rgeoc/?lnglat=%f,%f", lng, lat];
    NSString *data = [self fetchDataForUrlString:url];
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSDictionary *rtn = [parser objectWithString:data];
    [parser release];
    [pool release];
}


- (void)sendComment:(Comment *)comment
{
    if ([self connectToNetwork]) {
        [self performSelectorInBackground:@selector(backgroundSendComment:) withObject:comment];
    } else {
        [self.delegate requestFailWithProxy:self];
    }
}

- (void)backgroundSendComment:(Comment *)comment
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *url = [[PathHelper baseUrl] stringByAppendingFormat:@"c=user&a=addcomment"];
    NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:comment.content, @"content", [NSNumber numberWithInt:comment.dialectId], @"id", nil];
    NSString *rtn = [self postData:data files:nil url:url];
    NSDictionary *res = [self parse:rtn];
    
    if ([[res objectForKey:@"st"] intValue] == ServerStatusSuccess) {
        NSDictionary *dic = [res objectForKey:@"rs"];
        Comment *comment = [Comment commentWithDic:dic];
        self.object = comment;
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    }
    [pool release];
}

- (void)dialectsOfUser:(User *)user
{
    if ([self connectToNetwork]) {
        [self performSelectorInBackground:@selector(backgroundDialectsOfUser:) withObject:user];
    } else {
        [self.delegate requestFinishWithProxy:self];
    }
}

- (void)backgroundDialectsOfUser:(User *)user
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *url = [[PathHelper baseUrl] stringByAppendingString:@"c=user&a=dialect"];
    
    NSString *data = [self fetchDataForUrlString:url];
    NSDictionary *rtn = [self parse:data];
    if ([[rtn objectForKey:@"st"] intValue] == ServerStatusSuccess) {
        NSArray *dialectArr = [rtn objectForKey:@"rs"];
        [self performSelectorOnMainThread:@selector(storeDialects:) withObject:dialectArr waitUntilDone:YES];
        
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    }
    
    [pool release];
}


- (void)searchTerm:(NSString *)term
{
    if ([self connectToNetwork]) {
        [NSRunLoop cancelPreviousPerformRequestsWithTarget:self selector:@selector(backgroundSearchTerm:) object:term];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(backgroundSearchTerm:) object:term];
        [self performSelectorInBackground:@selector(backgroundSearchTerm:) withObject:term];
    } else {
        [self.delegate requestFinishWithProxy:self];
    }
}

- (void)backgroundSearchTerm:(NSString *)term
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSString *url = [[PathHelper baseUrl] stringByAppendingFormat:@"c=sentence&a=search&term=%@", term];
    
    NSString *data = [self fetchDataForUrlString:url];
    NSDictionary *rtn = [self parse:data];
    if ([[rtn objectForKey:@"st"] intValue] == ServerStatusSuccess) {
        NSArray *dialectArr = [rtn objectForKey:@"rs"];
        [self performSelectorOnMainThread:@selector(storeDialects:) withObject:dialectArr waitUntilDone:YES];
        
        [self.delegate performSelectorOnMainThread:@selector(requestFinishWithProxy:) withObject:self waitUntilDone:YES];
    }
    
    [pool release];
}


@end





